package leetcode.code0687;

import leetcode.helper.tree.TreeNode;

public class Solution {

	int ans;

	public int longestUnivaluePath(TreeNode root) {
		ans = 0;
		this.longestPath(root);
		return ans;
	}

	private int longestPath(TreeNode root) {
		if (root == null) {
			return 0;
		}
		int l = this.longestPath(root.left), r = this.longestPath(root.right);
		int L = 0, R = 0;
		if (root.left != null && root.val == root.left.val) {
			L = l + 1;
		}
		if (root.right != null && root.val == root.right.val) {
			R = r + 1;
		}
		ans = Math.max(ans, L + R);
		return Math.max(L, R);
	}

}
